/* eslint-disable */
import noTokenRequest from '@/utils/request';
import { stringify } from 'qs';
import { getAccessToken, getRefreshToken } from '@/utils/tokenStore';
import { refreshToken } from './token';

function logout() {
  window.g_app._store.dispatch({
    type: 'login/expired',
  });
}

/**
 * 带Token的请求, 返回Response
 * @param url
 * @param option
 */
export default function request(url, option) {
  const options = {
    ...option,
  };
  options.headers = {
    Authorization: `Bearer ${getAccessToken()}`,
    ...option.headers,
  };

  return noTokenRequest(url, options).then(response => {
    // token 失效
    if (response.status === 401) {
      // 重新获取token
      return new Promise(resolve => {
        const rfToken = getRefreshToken();
        if (!rfToken) logout();
        refreshToken(rfToken).then(response => {
          if (response.code === 0) {
            resolve(request(url, option));
          } else {
            logout();
          }
        });
      });
    } else {
      return response;
    }
  });
}

/**
 * 带Token的请求,返回Json
 * @param url
 * @param option
 */
export function requestJson(url, option) {
  return request(url, option).then(response => response.json());
}

/**
 * Json请求，快捷方法
 * @type {{
 *  get: (function(*=, *=, *)),
 *  post: (function(*=, *=, *)),
 *  postJson: (function(*=, *=, *))}}
 */
export const reqJson = {
  get: (url, param, option) => {
    if (param) url += `?${stringify(param)}`;
    return requestJson(url, {
      method: 'GET',
      ...option,
    });
  },
  post: (url, param, option) => {
    if (param) url += `?${stringify(param)}`;
    return requestJson(url, {
      method: 'POST',
      ...option,
    });
  },
  postJson: (url, param, option) => {
    return requestJson(url, {
      method: 'POST',
      body: param,
      ...option,
    });
  },
};
